package com.info33.platform.system.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info33.platform.common.mvc.vo.Result;
import com.info33.platform.system.dao.SysDistrictsDao;
import com.info33.platform.system.dos.Districts;
import com.info33.platform.system.entity.SysDistricts;
import com.info33.platform.system.service.SysDistrictsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author admin
 */
@Service
public class SysDistrictsServiceImpl extends ServiceImpl<SysDistrictsDao, SysDistricts> implements SysDistrictsService {

    @Autowired
    SysDistrictsDao sysDistrictsDao;

    /**
     * 更新行政区域信息
     * 调用第三方接口更新（高德）
     * keywords: 规则：只支持单个关键词语搜索关键词支持：行政区名称、citycode、adcode 例如，在subdistrict=2，搜索省份（例如山东），能够显示市（例如济南），区（例如历下区）
     * subdistrict: 规则：设置显示下级行政区级数（行政区级别包括：国家、省/直辖市、市、区/县4个级别）
     * 可选值：0、1、2、3
     * 0：不返回下级行政区；
     * 1：返回下一级行政区；
     * 2：返回下两级行政区；
     * 3：返回下三级行政区；
     * extensions: 此项控制行政区信息中返回行政区边界坐标点； 可选值：base、all;
     * base:不返回行政区边界坐标点；
     * all:只返回当前查询district的边界值，不返回子节点的边界值；
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Result<Object> refresh() {
        sysDistrictsDao.truncate();
        List<SysDistricts> saveList = new ArrayList<>();
        String s = HttpUtil.get("https://restapi.amap.com/v3/config/district?key=7e320fbb935de80aa6f96b245ab99b7d&subdistrict=1");
        List<Districts> districtsList = new JSONObject(s).getJSONArray("districts").toList(Districts.class);
        for (Districts districts : districtsList.get(0).getDistrictsList()) {
            SysDistricts entity = new SysDistricts();
            entity.setName(districts.getName());
            entity.setCityCode(districts.getCitycode());
            entity.setRegionCode(districts.getAdcode());
            entity.setCenterCoordinate(districts.getCenter());
            entity.setLevel(districts.getLevel());
            saveList.add(entity);
            getChildren(entity);
        }
        return this.saveBatch(saveList) ? Result.ok() : Result.error();
    }

    /**
     * 遍历子集
     *
     * @param sysDistrict -
     */
    private void getChildren(SysDistricts sysDistrict) {
        List<SysDistricts> saveList = new ArrayList<>();
        String s = HttpUtil.get("https://restapi.amap.com/v3/config/district?key=7e320fbb935de80aa6f96b245ab99b7d&subdistrict=1&keywords=" + sysDistrict.getRegionCode());
        List<Districts> districtsList = new JSONObject(s).getJSONArray("districts").toList(Districts.class);
        for (Districts districts : districtsList.get(0).getDistrictsList()) {
            SysDistricts entity = new SysDistricts();
            entity.setName(districts.getName());
            entity.setCityCode(districts.getCitycode());
            entity.setRegionCode(districts.getAdcode());
            entity.setCenterCoordinate(districts.getCenter());
            entity.setLevel(districts.getLevel());
            while (!"street".equals(districts.getLevel())) {
                getChildren(entity);
            }
            saveList.add(entity);
        }
        this.saveBatch(saveList);
    }
    
	@Override
	public String translateDistrictsId(String id) {
		return sysDistrictsDao.translateDistrictsId(id);
	}
}